//
//  NetShare.m
//  u76ho
//
//  Created by m-air-01 on 16/1/15.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "NetShare.h"
#import <CommonCrypto/CommonDigest.h>
#import "LoadingView.h"
#define cookieKey @"access_token"
static NetShare * netShare;
@interface NetShare ()
{
    NSString * appId;
}

@end
NetShare * request(void){
    NetShare * net = [NetShare shareNet];
    
    //设置请求返回格式
    [net.manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    net.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", nil];
    if (net.cookie) {
        [net.manager.requestSerializer setValue:net.cookie forHTTPHeaderField:cookieKey];
//        NSLog(@"接口token:%@",net.cookie);
    }
    //默认加载等待
    net.isWaiting = YES;
    return net;
}

@implementation NetShare
@synthesize isLogin = _isLogin,cookie = _cookie;
-(void)setIsLogin:(BOOL)isLogin
{
    _isLogin = isLogin;
    [NSUserDefaults setBool:isLogin forKey:isLogininged];
}
-(BOOL)isLogin
{
    return [NSUserDefaults boolForKey:isLogininged];
}
-(void)setCookie:(NSString *)cookie
{
    _cookie = cookie;
    if (cookie) {
        self.isLogin = YES;
        [NSUserDefaults setObject:cookie forKey:cookieKey];
    }
    else
    {
        self.isLogin = NO;
        [NSUserDefaults removeObjectForKey:cookieKey];
    }
}
-(NSString *)cookie
{
    return [NSUserDefaults objectForKey:cookieKey];
}
+(NetShare *)shareNet
{
    @synchronized(self) {
        if (!netShare) {
            netShare = [[NetShare alloc]init];
            netShare.manager = [AFHTTPRequestOperationManager manager];
            
            //netShare.manager.responseSerializer = [AFJSONResponseSerializer serializer];
            [netShare.manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
            netShare.manager.requestSerializer.timeoutInterval = 30.f;
               [netShare.manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
            //记录发起的所有网络状态
            netShare.waitingPool = [[NSMutableDictionary alloc]init];
        }
    }
    return netShare;
}
-(void)POST_URL:(NSString *)url pram:(id)dic finished:(finishBlock)finishedBlcok failed:(failedBlock)failBlock
{
    __weak typeof(self) weakSelf = self;
    //[self dealWaiting:url isBegin:YES];
    NSMutableDictionary * myDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    if ([dic isKindOfClass:[NSDictionary class]]) {
        [myDic setValue:[self appidCreate] forKey:@"appid"];
        [myDic setValue:[self appsecCreate] forKey:@"appsec"];
        [myDic setValue:[Singleton share].token ? [Singleton share].token : @"" forKey:@"token"];
    }
    [_manager POST:url parameters:myDic success:^(AFHTTPRequestOperation * operation, id responseObject) {
        [weakSelf dealSession:operation];
        //[weakSelf dealWaiting:url isBegin:NO];
        
        if (responseObject) {
            int i = [[responseObject objectForKey:@"errcode"] intValue];
            if (i == 200) {
                
                [Singleton share].code = nil;
                [Singleton share].mobile = nil;
                [Singleton share].yqcode = nil;
                [Singleton share].userInformation = nil;
                [Singleton share].token = nil;
                [[Singleton share] saveUserInformation];
                [Singleton alerSendMessage:@"token失效，请重新登录"];
            }
        }
        
        
        finishedBlcok(responseObject);
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        //[weakSelf dealWaiting:url isBegin:NO];
        NSString * msg = nil;
        if ([operation.responseObject isKindOfClass:[NSDictionary class]]) {
            msg = operation.responseObject[@"msg"];
        }
        if (!msg) {
            msg = error.localizedDescription;
        }
        if ([msg isEqualToString:@"似乎已断开与互联网的连接。"]) {
            [Singleton alerSendMessage:@"似乎已断开与互联网的连接"];
            
            
        }
        failBlock(msg);
    }];
}
-(void)GET_URL:(NSString *)url pram:(NSDictionary *)dic finished:(finishBlock)finishedBlcok failed:(failedBlock)failBlock
{
    __weak typeof(self) weakSelf = self;
    [self dealWaiting:url isBegin:YES];
    [_manager GET:url parameters:dic success:^(AFHTTPRequestOperation * operation, id responseObject) {
        [weakSelf dealSession:operation];
        [weakSelf dealWaiting:url isBegin:NO];
        finishedBlcok(responseObject);
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        [weakSelf dealWaiting:url isBegin:NO];
        NSString * msg = nil;
        if ([operation.responseObject isKindOfClass:[NSDictionary class]]) {
            msg = operation.responseObject[@"msg"];
        }
        if (!msg) {
            msg = error.localizedDescription;
        }
        failBlock(msg);
    }];
}
-(void)PUT_URL:(NSString *)url pram:(id)dic finished:(finishBlock)finishedBlcok failed:(failedBlock)failBlock
{
    __weak typeof(self)weakSelf = self;
    [self dealWaiting:url isBegin:YES];
    [_manager PUT:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [weakSelf dealSession:operation];
        [weakSelf dealWaiting:url isBegin:NO];
        finishedBlcok(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf dealWaiting:url isBegin:NO];
        NSString * msg = nil;
        if ([operation.responseObject isKindOfClass:[NSDictionary class]]) {
            msg = operation.responseObject[@"msg"];
        }
        if (!msg) {
            msg = error.localizedDescription;
        }
        failBlock(msg);
    }];

}
-(void)DELETE_URL:(NSString *)url pram:(NSDictionary *)dic finished:(finishBlock)finishedBlcok failed:(failedBlock)failBlock
{
    __weak typeof(self)weakSelf = self;
    [self dealWaiting:url isBegin:YES];
    [_manager DELETE:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [weakSelf dealSession:operation];
        [weakSelf dealWaiting:url isBegin:NO];
        finishedBlcok(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf dealWaiting:url isBegin:NO];
        NSString * msg = nil;
        if ([operation.responseObject isKindOfClass:[NSDictionary class]]) {
            msg = operation.responseObject[@"msg"];
        }
        if (!msg) {
            msg = error.localizedDescription;
        }
        failBlock(msg);
    }];

}

//上传图片
- (void)POST_URL:(NSString *)url updataImage:(UIImage *)image pram:(NSDictionary * )dic finished:(finishBlock)finishedBlcok failed:(failedBlock)failBlock{
    
    __weak typeof(self)weakSelf = self;
    NSMutableDictionary * myDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    if ([dic isKindOfClass:[NSDictionary class]]) {
        [myDic setValue:[self appidCreate] forKey:@"appid"];
        [myDic setValue:[self appsecCreate] forKey:@"appsec"];
    }
    [self dealWaiting:url isBegin:YES];
    [_manager POST:url parameters:myDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
            NSString * type = @"image/jpeg";
            NSString * names = @".jpg";
           //压缩图片大小
            UIImage * newImg = [self fixOrientation:image];
           //压缩像素
            NSData * dataImage=[weakSelf imageData:newImg];
            if (dataImage==nil) {
                dataImage = UIImagePNGRepresentation(image);
                type = @"image/png";
                names = @".png";
            }
            [formData appendPartWithFileData:dataImage name:@"pictures" fileName:@"image.jpg" mimeType:type];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        [weakSelf dealSession:operation];
        [weakSelf dealWaiting:url isBegin:NO];
        finishedBlcok(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf dealWaiting:url isBegin:NO];
        NSString * msg = nil;
        if ([operation.responseObject isKindOfClass:[NSDictionary class]]) {
            msg = operation.responseObject[@"msg"];
        }
        if (!msg) {
            msg = error.localizedDescription;
        }
        failBlock(msg);
    }];
}
-(UIImage *)fixOrientation:(UIImage *)img
{
    if (img.imageOrientation == UIImageOrientationUp) {
        return img;
    }
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (img.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.width, img.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, img.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
            
        default:
            break;
    }
    
    switch (img.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
        default:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, img.size.width, img.size.height,
                                             CGImageGetBitsPerComponent(img.CGImage), 0,
                                             CGImageGetColorSpace(img.CGImage),
                                             CGImageGetBitmapInfo(img.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (img.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            
            CGContextDrawImage(ctx, CGRectMake(0, 0, img.size.height, img.size.width), img.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0, 0, img.size.width, img.size.height), img.CGImage);
            break;
    }
    
    CGImageRef cging = CGBitmapContextCreateImage(ctx);
    UIImage * newImg = [UIImage imageWithCGImage:cging];
    CGContextRelease(ctx);
    CGImageRelease(cging);
    
    return newImg;
    
}

#pragma mark--压缩图片
/*处理图片*/
-(NSData *)imageData:(UIImage *)myimage
{
    NSData *data=UIImageJPEGRepresentation(myimage, 1.0);
    if (data.length>100*1024) {
        if (data.length>4*1024*1024) {//4M以及以上
            data=UIImageJPEGRepresentation(myimage, 0.01);
        }else if (data.length>1024*1024) {//1M-4M
            data=UIImageJPEGRepresentation(myimage, 0.1);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(myimage, 0.5);
        }else if (data.length>200*1024) {//0.25M-0.5M
            data=UIImageJPEGRepresentation(myimage, 0.9);
        }
    }
    return data;
}

/*处理网络加载状态逻辑*/
- (void)dealWaiting:(NSString *)url isBegin:(BOOL)yes{
    if (yes) {
        if (_isWaiting) {
            [_waitingPool setObject:@(_isWaiting) forKey:url];
            [LoadingView loadingView];
        }//以下注释会影响加载状态,会造成之前请求数据没有成功就移除加载状态
        //        else{
        //            [LoadingView loadingView];
        //        }
    }else{
        if ([_waitingPool objectForKey:url]) {
            [_waitingPool removeObjectForKey:url];
            BOOL haveWaiting = NO;
            for (NSNumber * sub in _waitingPool.allValues) {
                if ([sub boolValue]) {
                    haveWaiting = YES;
                    break;
                }
            }
            if (!haveWaiting)[LoadingView removeLoadingView];
        }
    }
}
/*存储登录状态session*/
- (void)dealSession:(AFHTTPRequestOperation *)operation{
    //存储登录状态session
    NSString *cookieString = [[operation.response allHeaderFields] valueForKey:cookieKey];
    if (cookieString != nil && ![cookieString isEqualToString:@""]) {
        self.cookie=cookieString;
    }
}


//appid和appsec的生成
-(NSString *)appidCreate
{
    NSDate * date = [NSDate date];
    NSInteger dataCH = [date timeIntervalSince1970];
    NSString * dateStr = [NSString stringWithFormat:@"%i",(int)dataCH];
    appId = dateStr;
    return dateStr;
}
-(NSString *)appsecCreate
{
    NSString * subStr = [appId substringToIndex:8];
    NSString * lastStr = [appId substringWithRange:NSMakeRange(appId.length-1, 1)];
    
    NSString * replaceStr;
    if ([lastStr isEqualToString:@"0"]) {
        replaceStr = @"yq2015h";
    }
    else if ([lastStr isEqualToString:@"1"])
    {
        replaceStr = @"lh20q16";
    }
    else if ([lastStr isEqualToString:@"2"])
    {
        replaceStr = @"yh15y12";
    }else if ([lastStr isEqualToString:@"3"])
    {
        replaceStr = @"yh15yqlh1212";
    }else if ([lastStr isEqualToString:@"4"])
    {
        replaceStr = @"yqlh16lh0101";
    }else if ([lastStr isEqualToString:@"5"])
    {
        replaceStr = @"lh16lh02yq";
    }else if ([lastStr isEqualToString:@"6"])
    {
        replaceStr = @"yq51ll131";
    }else if ([lastStr isEqualToString:@"7"])
    {
        replaceStr = @"20ll01yy28";
    }else if ([lastStr isEqualToString:@"8"])
    {
        replaceStr = @"yy61ll01";
    }else if ([lastStr isEqualToString:@"9"])
    {
        replaceStr = @"yqhl502131";
    }
    
    NSString * hechengStr = [NSString stringWithFormat:@"%@%@",subStr,replaceStr];
    return [self md5:hechengStr];
}

-(NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];//转换成utf-8
    unsigned char result[16];//开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    CC_MD5( cStr, (int)strlen(cStr), result);
    /*
     extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把cStr字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了result这个空间中
     */
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     NSLog("%02X", 0x888);  //888
     NSLog("%02X", 0x4); //04
     */
}
@end
